import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from book.models import BookInfo


# Create your views here.
# 查询所有图书、增加图书
class BooksView(View):

    def post(self, request):
        """
            新增图书
            路由：POST /books/
        """
        """
            传递形式是json
            btitle  str  必须   图书名称
            bpub_date  date 必须 上架时间
            bread   int  非必须  阅读量
            bcomment  int 非必须  评论量
            is_delete bool 非必须  逻辑删除
        """
        # 1.获取前端数据
        data = request.body.decode()
        data_dict = json.loads(data)
        btitle = data_dict.get("btitle")
        bpub_date = data_dict.get('bpub_date')
        bread = data_dict.get('bread')
        bcomment = data_dict.get('bcomment')

        # 2、验证数据
        # 验证btitle和bpub_date是否传递
        if not all([btitle, bpub_date]):
            return JsonResponse({'error': "数据不完整"}, status=400)
        # 验证书名长度
        if len(btitle) > 20:
            return JsonResponse({'error': "图书名字不能大于20字"}, status=400)

        # 3、保存图书
        book = BookInfo.objects.create(**data_dict)

        # 返回结果
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        })

    def get(self, request):
        """
            获取所有图书
        :param request:
        :return:
        """
        # 1、查询数据库获取所有图书
        books = BookInfo.objects.all()
        book_list = []
        # 2、提取数据字段
        for book in books:
            book_list.append({
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment
            })

        # 3、返回结果
        return JsonResponse({'book_list': book_list})


# 获取一本图书 , 更新, 删除
class BookView(View):

    def get(self, request, pk):
        """
            获取单一图书
            路由： GET  /books/<pk>/
        :param request:
        :return:
        """
        # 1、根据id值查询数据库
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': 'id不存在'}, status=400)
        # 2、返回数据
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        })

    def put(self, request, pk):
        """
            更新图书
            路由： PUT  /books/<pk>
        :param request:
        :return:
        """
        # 1、获取前端数据
        data = request.body.decode()
        data_dict = json.loads(data)
        btitle = data_dict.get('btitle')
        bpub_date = data_dict.get('bpub_date')
        bread = data_dict.get('bread')
        bcomment = data_dict.get('bcomment')
        # 2、验证数据
        # 验证书名长度
        if btitle:
            if len(btitle) > 20:
                return JsonResponse({'error': "图书名字不能大于20字"}, status=400)
        # 3、更新图书
        res = BookInfo.objects.filter(id=pk).update(**data_dict)
        if res == 0:
            return JsonResponse({'error': '更新失败'})
        # 获取更新后的数据
        book = BookInfo.objects.get(id=pk)
        # 4、返回结果
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        })

    def delete(self, request, pk):
        """
              删除图书
              路由： DELETE /books/<pk>/
          :param request:
          :return:
         """
        # 1、根据id值查询数据库,获取删除的图书
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': 'id不存在'}, status=400)

        # 2、删除图书  逻辑删除 物理删除
        # book.delete()# 物理删除
        book.is_delete = True
        book.save()
        return JsonResponse({})
